package com.hjimi.ski.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created By 孙岩
 * on 2023/10/12
 */
public class ImageProvider {
    private static final String IMAGE_CACHE_DIR = "images";

    public List<String> loadImagesFromUrl(List<String> imageUrls) {
        List<String> localImages = new ArrayList<>();

        for (String imageUrl : imageUrls) {
            String imageName = getImageName(imageUrl);
            Bitmap bitmap = downloadAndCacheImage(imageUrl, imageName);
            if (bitmap != null) {
                localImages.add(imageName);
            }
        }
        return localImages;
    }

    private Bitmap downloadAndCacheImage(String imageUrl, String imageName) {
        Bitmap bitmap = null;
        File imageFile = new File(Environment.getExternalStorageDirectory(), IMAGE_CACHE_DIR + "/" + imageName);
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(60000); // 1 minute timeout
            conn.setReadTimeout(60000); // 1 minute timeout
            conn.setDoInput(true);
            conn.connect();
            int responseCode = conn.getResponseCode();
            if(responseCode == 200) {
                InputStream is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);
                is.close();
                FileOutputStream fos = new FileOutputStream(imageFile);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    private String getImageName(String imageUrl) {
        // Implement your logic here to get the image name from the URL. For simplicity, we're just using the URL itself as the file name.
        return imageUrl;
    }
}
